import axios from "axios"
import constants from "@/common/constants"
import cacheUtil from "@/util/cacheUtil"
import router from "@/router/index"

const service = axios.create({
	baseURL:constants.HTTP_CONFIG.baseUrl,
	timeout:constants.HTTP_CONFIG.timeout
})

// 请求拦截
service.interceptors.request.use(
config =>{
	// 从缓存去除token
	const userInfo = cacheUtil.getlocalstroge('userInfo')
	if(userInfo && userInfo.token){
		config.headers.token = userInfo.token
	}
	return config
},error =>{
	console.log(error);
})

// 响应拦截器
service.interceptors.response.use(
response=>{
	const res = response.data;
	if(res.code == 2){
		router.push('/')
	}
	return res
},error =>{
		if(error && error.response){
			switch (error.message.status){
				case 404:error.message = '当前页面不存在'
					break;
				case 500:error.message = '服务器错误'
					break;
			}
		}
		if(error.message.includes('timeout')){
			error.message = '请求超时'
		}
		return Promise.reject(error.message)
})
export default service